#include <iconv.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "buffer.h"
#include "characterset.h"
#include <string>
using namespace std;

int CharacterSetTransform :: Transform( char * psSrc, size_t srcLen,
	   	const char * eSrcSet, char * psDest, size_t & destLen, const char * eDestSet )
{
	int ret = -1;
	
	iconv_t cd = iconv_open( eSrcSet, eDestSet);
	
	if ( cd >= 0 )
	{
		int size = (int)iconv( cd, &psSrc, &srcLen, &psDest, &destLen );
		
		if ( srcLen == size )
		{
			ret = 0;
		}
		else if ( size != srcLen && size >= 0 )//size != -1 && size != srcLen )
		{
			printf("size %d srclen %d errno %d errmsg %s\n",size,srcLen,errno,strerror(errno));
			ret = -2;
		}
		else
		{
			printf("size %d srclen %d errno %d errmsg %s\n",size,srcLen,errno,strerror(errno));
			ret = -1;
		}
		iconv_close( cd );
	}
	else
		printf("iconv_open fail, errno %d errmsg %s\n", errno, strerror(errno) );
	
	return ret;
}

int CharacterSetTransform :: Transform( Buffer * ptInBuf, const char * eIn, Buffer * ptOutBuf, const char * eOut )
{

	int ret = -1;
	size_t outlen = (size_t) ptOutBuf->GetCapability();
	char * psSrc = ptInBuf->GetByteBuffer();
	size_t inlen = (size_t) ptInBuf->GetLimit();
	char * psDest = ptOutBuf->GetByteBuffer();
	iconv_t cd = iconv_open( eIn, eOut );

	if ( cd >= 0 )
	{
		int size = (int) iconv( cd, &psSrc , &inlen, &psDest, &outlen );
		
		if ( ptInBuf->GetLimit() == size )
		{
			ret = 0;
		}
		else if ( size != ptInBuf->GetLimit() && size >= 0 )//size != -1 && size != srcLen )
		{
			//printf("size %d srclen %d errno %d errmsg %s\n",size,srcLen,errno,strerror(errno));
			ret = -2;
		}
		else
		{
			//printf("size %d srclen %d errno %d errmsg %s\n",size,srcLen,errno,strerror(errno));
			ret = -1;
		}
		iconv_close( cd );
	}
	else
		printf("iconv_open fail, errno %d errmsg %s\n", errno, strerror(errno) );

	if ( ret == 0 )
		ptOutBuf->SetLimit( outlen );
	return ret;
}
